# -*- coding: utf-8  -*-
#!/usr/local/bin/python

__author__ = 'yaojian'

from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader, Context
from django.utils.http import urlunquote, urlquote
from decorators import getDefaultChannel, getDoUrl, sso_user_reg, setCookie, sso_user_login, getChannelDomain
from misc.errorcode import ERROR_CODE
from django import template
from ws.decorators import compile_response

def user_login_view(request):
    _context = template.RequestContext(request)
    _profile = None
    _result = False
    _Token = None
    _uname = request.parameters.get('username')
    _password = request.parameters.get('password')
    _errorcode, _mes, _profile, _Token = sso_user_login(_uname, _password)
    if _errorcode == ERROR_CODE.SUCCESS:
        _result = True
    _extra_context = {
        "result"        : _result,
        "errorcode"     : _errorcode,
        "message"       : _mes,
        "profile"       : _profile,
        "token"         : _Token
    }
    _context.update(_extra_context)
    _response = compile_response(request, 'ws/sso/ssologin.xml', _context)
    return _response, _result, _mes, _extra_context

def web_user_reg_view(request):
    if 'uid' in request.COOKIES and request.COOKIES['uid'] is not None and request.COOKIES['uid'] != '':
        url = getDefaultUrl()
        mes = u'您已经登陆，跳转到您的个人主页'
        go = url + mes
        return HttpResponseRedirect(go)
    tem = loader.get_template('sso/web_user_reg.html')
    surl = request.parameters.get('surl')
    eurl = request.parameters.get('eurl')
    channel = request.parameters.get('channel')
    if(surl is None):
        surl = ''
    else:
        surl = urlquote(surl)

    if(eurl is None):
        eurl = ''
    else:
        eurl = urlquote(surl)

    if channel is None or channel == '':
        channel = getDefaultChannel()
    dourl = getDoUrl(channel, 'reg')
    t = Context({'surl': surl, 'eurl': eurl, 'dourl': dourl})
    return HttpResponse(tem.render(t))

def web_user_do_reg_view(request):
    response, result, errormes, data = user_reg_view(request)
    surl = request.parameters.get('surl')
    eurl = request.parameters.get('eurl')
    channel = request.parameters.get('channel')
    if channel is None or channel == '':
        channel = getDefaultChannel()
    if result is True:
        if surl is None or surl == '' or surl == '/':
            url = getDefaultUrl(channel, True)
            mes = u'您已成功注册成为小橙子用户'
            go = url + mes
        else:
            go = urlunquote(surl)
        httpobj = HttpResponseRedirect(go)
        valueDice = {'token': data['token'], 'uid' : data['profile'].id, 'nick' : data['profile'].nickname}
        setCookie(valueDice, channel, httpobj, 'set', True)
    else:
        if eurl is None or eurl == '':
            eurl = getDefaultUrl(channel, False)
            mes = u'注册失败。原因:' + errormes
            go = eurl + mes
        else:
            go = urlunquote(eurl)
        httpobj = HttpResponseRedirect(go)
    return httpobj


def user_reg_view(request):
    uname = request.parameters.get('username')
    password = request.parameters.get('password')
    channel = request.parameters.get('channel')
    if channel == '' or channel is None:
        channel = 'littleOrange'
    _context = template.RequestContext(request)
    _profile = None
    _result = False
    _Token = None
    _uname = request.parameters.get('username')
    _password = request.parameters.get('password')
    _errorcode, _mes, _profile, _Token = sso_user_reg(uname, password, channel)
    if _errorcode == ERROR_CODE.SUCCESS:
        _result = True
    _extra_context = {
        'result' : _result,
        'errorcode' : _errorcode,
        'message' : _mes,
        'profile' : _profile,
        'token' : _Token
    }
    _context.update(_extra_context)
    _response = compile_response(request, 'ws/sso/ssologin.xml', _context)
    return _response, _result, _mes, _extra_context

def test_user_reg_view(request):
    request.CUSTOM_VARY = True
    context = template.RequestContext(request)
    _channel = request.parameters.get("channel")
    if _channel is None or _channel == "":
        _channel = "littleOrange"
    _output = request.parameters.get("output")
    _username = request.parameters.get("username")
    _password = request.parameters.get("password")
    _result = True
    _errorcode = ERROR_CODE.SUCCESS
    _message = ERROR_CODE.SUCCESS

    extra_context = {
        "result" : _result,
        "code"  : _errorcode,
        "messgae" : _message,
        "channel" : _channel,
        "output" : _output,
        "username" : _username,
        "password" : _password,
    }

    context.update(extra_context);
    response = compile_response(request, "ws/sso/testSSOReg.xml", context)
    return response



def getDefaultUrl(channel = None, result = True):
    urlSucc = {'littleOrange': 'http://127.0.0.1:8000/ws/sso/web/sso-view-html?mes=',
               'sso': 'http://127.0.0.1:8000/ws/sso/web/sso-view-html?mes='}
    urlError = {'littleOrange' : 'http://127.0.0.1:8000/ws/sso/web/sso-view-html?mes=',
                'sso' : 'http://127.0.0.1:8000/ws/sso/web/sso-view-html?mes='}
    if result is False:
        return urlError[channel] if channel in urlError else urlError['sso']
    return urlSucc[channel] if channel in urlSucc else urlSucc['sso']

def web_sso_mes_view(request):
    mes = request.parameters.get('mes')
    tem = loader.get_template('sso/error.html')
    t = Context({'mes' : mes})
    return HttpResponse(tem.render(t))

def web_user_login_view(request):
    if 'uid' in request.COOKIES and request.COOKIES['uid'] is not None and request.COOKIES['uid'] != '':
        url = getDefaultUrl();
        mes = u'您已经登陆，跳转到您的个人主页'
        go = url + mes
        return HttpResponseRedirect(go)

    tem = loader.get_template('sso/user_login.html')
    surl = request.parameters.get('surl')
    eurl = request.parameters.get('eurl')
    channel = request.parameters.get('channel')

    if (surl is None):
        surl = ""
    else:
        surl = urlquote(surl)

    if eurl is None:
        eurl = ""
    else:
        eurl = urlquote(eurl)

    if channel is None or channel == '':
        channel = getDefaultChannel()
    dourl = getDoUrl(channel, 'login')
    t = Context({'surl' : surl, 'eurl' : eurl, 'dourl' : dourl})
    return HttpResponse(tem.render(t))

def web_user_do_login_view(request):
    response, result, errormes, data = user_login_view(request)
    surl = request.parameters.get('surl')
    eurl = request.parameters.get('eurl')
    channel = request.parameters.get('channel')

    if result is True:
        if surl == '' or surl is None or surl == "/":
            url = getDefaultUrl(channel)
            mes = u'您已经成功登陆'
            go = url + mes
        else:
            go = urlunquote(surl)
        httpobj = HttpResponseRedirect(go)
        valueDic = {'token' : data['token'], 'uid' : data['profile'].id, 'nick' : data['profile'].nickname}
        setCookie(valueDic, channel, httpobj, 'set', True)
    else:
        if eurl is None or eurl == '' or eurl == '/':
            url = getDefaultUrl(channel, False)
            mes = u"登陆失败错误原因：" + errormes
            go = url + mes
        else:
            go = urlunquote(eurl)
        httpobj = HttpResponseRedirect(go)
    return httpobj

def loginout_view(request):
    url = request.parameters.get('redirect')
    channel = request.parameters.get('channel')
    if channel is None or channel == '':
        channel = getDefaultChannel()
    if url is None or url == '':
        try:
            url = request.META['HTTP_REFERER']
        except Exception:
            url = "http://localhost:8000/main"
    response = HttpResponseRedirect(url)
    domain = getChannelDomain(channel)
    return response